package com.example.iwalk.newprintapplication.imp;

import com.example.iwalk.newprintapplication.constant.SocketState;
import com.example.iwalk.newprintapplication.inter.Printer;
import com.example.iwalk.newprintapplication.inter.SocketStateChangeListener;

import java.io.IOException;
import java.io.OutputStream;

/**
 * 打印机实现类
 * Created by iwalk on 2016/12/16.
 */

public abstract class PrinterImp implements Printer {
    public abstract int getType();

    @Override
    public void print(OutputStream socketOut, byte[] data, SocketStateChangeListener stateChangeListener) {
        try {
            if (socketOut == null) {
                return;
            }
            socketOut.write(data);
            stateChangeListener.onStateChanged(SocketState.STATE_3);
        } catch (IOException e) {
            e.printStackTrace();
            stateChangeListener.onConnectFailed(SocketState.ERROR_3);
        }
    }

    /**
     * 判断是否中文
     * GENERAL_PUNCTUATION 判断中文的“号
     * CJK_SYMBOLS_AND_PUNCTUATION 判断中文的。号
     * HALFWIDTH_AND_FULLWIDTH_FORMS 判断中文的，号
     *
     * @param c 字符
     * @return 是否中文
     */
    public static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        return ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
                || "×".equals(new String(new char[]{c}));
    }

    /**
     * 正则表达式判断汉字
     *
     * @param value
     * @return
     */
    public static int String_length(String value) {
        int valueLength = 0;
        String chinese = "[\u4e00-\u9fa5]";
        for (int i = 0; i < value.length(); i++) {
            String temp = value.substring(i, i + 1);
            if (temp.matches(chinese)) {
                valueLength += 2;
            } else {
                valueLength += 1;
            }
        }
        return valueLength;
    }
}
